package com.cans.lightning.business.pms.web;

import com.cans.lightning.base.dto.ResDto;
import com.cans.lightning.business.core.service.TokenService;
import com.cans.lightning.business.pms.dto.LoginBody;
import com.cans.lightning.business.pms.dto.SysUserDto;
import com.cans.lightning.business.pms.entity.SysUser;
import com.cans.lightning.business.pms.service.api.ISendMailService;
import com.cans.lightning.business.pms.service.api.ISysUserService;
import com.cans.lightning.business.pms.service.impl.SysLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.util.Random;

/**
 * 权限管理门户
 *
 * @author shencan
 * @date 2020/6/21 11:38
 */
@Slf4j
@RestController
@RequestMapping("/pms")
public class PmsController {

    @Resource
    private SysLoginService sysLoginService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;
    @Resource
    private TokenService tokenService;
    @Resource
    private ISendMailService sendMailService;


    /**
     * 登录
     *
     * @param loginBody 登录参数
     * @return
     */
    @PostMapping("/login")
    public ResDto<LoginBody> login(@RequestBody LoginBody loginBody) {
        // 生成令牌
        try {
            String token = sysLoginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode());
            loginBody.setToken(token);
            loginBody.setKey(loginBody.getUsername());
            loginBody.setPassword(null);
            return ResDto.success(loginBody);
        } catch (RedisConnectionFailureException e) {
            log.warn("Redis 连接错误", e);
            return ResDto.fait("redis连接错误请联系管理员");
        } catch (Exception e) {
            log.warn("用户名密码错误", e);
            return ResDto.fait("用户名密码错误");
        }
    }

    /**
     * 登出
     *
     * @return
     */
    @GetMapping("/loginOut")
    public ResDto<LoginBody> loginOut() {
        sysLoginService.loginOut();
        return ResDto.success();
    }


    /**
     * 注册
     *
     * @param registerBody 注册参数
     * @return
     */
    @PostMapping("/register")
    public ResDto<LoginBody> register(@RequestBody LoginBody registerBody) {
        if(registerBody.getUsername() == null){
            return ResDto.fait("用户名为空");
        }
        SysUser byUsername = sysUserService.getByUsername(registerBody.getUsername());
        if (byUsername != null) {
            return ResDto.fait("用户名[" + registerBody.getUsername() + "]已注册");
        }
        SysUser sysUser = new SysUser();
        // 用户名
        sysUser.setEmail(registerBody.getEmail());
        sysUser.setUsername(registerBody.getUsername());
        // 默认创建的都是超级管理员
        sysUser.setSuperMan(1);
        // 密码
        sysUser.setPassword(passwordEncoder.encode(registerBody.getPassword()));
        sysUserService.saveOrUpdate(sysUser);
        return ResDto.success();
    }

    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    @GetMapping("/get-current-user")
    public ResDto<SysUserDto> getCurrentUser() {

        SysUserDto sysUserDto = sysUserService.toDto(sysUserService.getCurrentUser());

        sysUserDto.setPassword(null);

        return ResDto.success(sysUserDto);
    }


    @GetMapping("/refresh")
    public void refresh() {
        SysUser currentUser = sysUserService.getCurrentUser();

        SysUserDto sysUserDto = sysUserService.toDto(currentUser);

        tokenService.refreshToken(sysUserDto);
    }

    /**
     * 注册发送email
     *
     * @param loginBody
     * @return
     */
    @PostMapping("/senEmail")
    public ResDto sendEmail(@RequestBody LoginBody loginBody) throws MessagingException {

        String code = String.format("%04d", new Random().nextInt(9999));

        sendMailService.sendMail(loginBody.getEmail(), "重置密码你的验证码", String.valueOf(code));

        return ResDto.success("验证码已发送,有效时间5分钟");
    }

    /**
     * 重置密码
     *
     * @param loginBody
     * @return
     */
    @PostMapping("/resetPassword")
    public ResDto resetPassword(@RequestBody LoginBody loginBody) throws MessagingException {

        sysUserService.resetPassword(loginBody.getEmail(), loginBody.getPassword(), loginBody.getCode());

        return ResDto.success("[" + loginBody.getEmail() + "]密码已重置");
    }

}
